#!/usr/bin/env tclsh
# $Id: test5.tcl 9ce65bed8ef4 2012/08/26 02:14:51 pgurumur $
# Copyright (c) 2012 Prabhu Gurumurthy <pgurumur@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

# __version__  = "$Revision: 9ce65bed8ef4 $"
# __author__   = "$Author: pgurumur $"
# __modified__ = "$Date: 2012-08-26 02:14:51Z $"

proc hex2int value {
   set retval 0
   scan $value %x retval
   return $retval
}

proc ipv6pack address {
   set ipint 0
   set records [split $address ":"]
   foreach rec $records {
      set ipint [expr [expr $ipint << 16] + [hex2int $rec]]
   }

   return $ipint
}

proc pack2ipv6 number {
   puts [expr ceil(pow(2,32))]
   set hextet4 [expr $number % pow(2,32)]
   set hextet3 [expr [expr $number >> 32] % int(pow(2,32))]
   set hextet2 [expr [expr $number >> 64] % int(pow(2,32))]
   set hextet1 [expr [expr $number >> 64] >> 32]
   set ipv6addr [concat [format %x $hextet1][format %x $hextet2][
      format %x $hextet3][format %x $hextet4]]

   return $ipv6addr
}

# set address [ipv6pack "2001:470:1f05:29d:215:c5ff:fe78:5fb6"]
# set address [ipv6pack $argv]
# set ipv6 [pack2ipv6 $address]
# puts "$argv: $address $ipv6"
#

proc getsize number {
   set ipvalmax 0
   set maxval 0
   set version 6
   if {$version == 4} {
      set ipvalmax 32
      set maxval [expr [expr 2 << 31] - 1]
      if {$maxval <= 0} {
         set maxval [expr round(pow(2,32)) - 1]
      }
   } elseif {$version == 6} {
      set ipvalmax 128
      set maxval [expr [expr 2 << 127] - 1]
      if {$maxval <= 0} {
         set maxval [expr round(pow(2,128)) - 1]
      }
   }

   set operator [expr $ipvalmax - $number]
   set maskval [expr 1 << $operator]

   return [expr [expr $maxval ^ $maskval] + 1]
}

set maxlong [expr round(pow(2, 128))]
foreach sz [list 8 16 24 32 40 48 56 64 72 80 88 96 108 112 128] {
   puts $sz
   puts [expr $maxlong - [getsize $sz]]
}

